package com.runda.system.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import com.bbjob.mapper.SysOrganizationMapper;
import com.bbjob.mapper.SysUserRoleMapper;
import com.bbjob.mapper.UserMapper;
import com.bbjob.model.SysOrganization;
import com.bbjob.model.SysUserRole;
import com.bbjob.model.User;
import com.bbjob.util.Tool;
import com.bbjob.util.service.impl.BaseService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.runda.entity.JwtUser;
import com.runda.system.service.UserService;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

@Service
public class UserServiceImpl extends BaseService<User> implements UserService, UserDetailsService {

	@Autowired
	private UserMapper usermapper;
	@Autowired
	private SysUserRoleMapper userrolemapper;
	@Autowired
	private SysOrganizationMapper organmapper;
	@Autowired
	private BCryptPasswordEncoder encoder;
	@Autowired
	private SysOrganizationMapper sysOrganizationMapper;

	@Override
	public int saveUser(User user) {
		// TODO Auto-generated method stub
		Example example = new Example(User.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("username", user.getUsername());
		List<User> resultList = usermapper.selectByExample(example);
		if (resultList.size() > 0) {
			// 用户名已存在
			return -1;
		}
		user.setCreateTime(new Date());
		user.setEnable(1);
		user.setPassword(encoder.encode(Tool.MD5("123456")));
		int ok = usermapper.insertSelective(user);
		return ok;
	}

	@Override
	public int editUser(User user) {
		// TODO Auto-generated method stub
		user.setUsername(null);
		user.setPassword(null);
		int ok = usermapper.updateByPrimaryKeySelective(user);
		return ok;
	}

	@Override
	public int deleteUser(Integer id) {
		// TODO Auto-generated method stub
		int ok = usermapper.deleteByPrimaryKey(id);
		return ok;
	}

	@Override
	public PageInfo<User> getlist(User user, int page, int size) {
		Map<Integer, String> map = new HashMap<>();
		List<SysOrganization> list = organmapper.selectAll();
		for (SysOrganization sysOrganization : list) {
			map.put(sysOrganization.getId(), sysOrganization.getName());
		}
		PageHelper.startPage(page, size);
		Example example = new Example(User.class);
		Example.Criteria criteria = example.createCriteria();
		if (StringUtil.isNotEmpty(user.getUsername())) {
			criteria.andLike("username", "%" + user.getUsername() + "%");
		}
		example.setOrderByClause(" create_time desc");
		List<User> resultList = usermapper.selectByExample(example);
		for (User user2 : resultList) {
			user2.setOrganname(map.get(user2.getOrganId()));
		}
		PageInfo<User> result = new PageInfo<User>(resultList);
		return result;
	}

	@Override
	public int setUserToRole(Integer userid, String role) {
		// TODO Auto-generated method stub
		String[] roleid = role.split(",");
		Example example = new Example(SysUserRole.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("userId", userid);
		userrolemapper.deleteByExample(example);
		if (StringUtil.isNotEmpty(role)) {
			for (int i = 0; i < roleid.length; i++) {
				SysUserRole sys = new SysUserRole();
				sys.setRoleId(Integer.parseInt(roleid[i]));
				sys.setUserId(userid);
				userrolemapper.insertSelective(sys);
			}
			return 1;
		} else {
			return 1;
		}

	}

	@Override
	public List<Integer> getauth(Integer userid) {
		// TODO Auto-generated method stub
		Example example = new Example(SysUserRole.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("userId", userid);
		List<SysUserRole> userrole = userrolemapper.selectByExample(example);
		List<Integer> list = new ArrayList<Integer>();
		for (SysUserRole sysUserRole : userrole) {
			list.add(sysUserRole.getRoleId());
		}
		return list;
	}

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		User user = new User();
		user.setUsername(username);
		User result = this.mapper.selectOne(user);
		if (result == null) {
			throw new UsernameNotFoundException("账户或密码不正确");
		}
		List<SimpleGrantedAuthority> authorities = null;
		if (result.getType() == -1) {
			authorities = new ArrayList<SimpleGrantedAuthority>();
			authorities.add(new SimpleGrantedAuthority("-1"));
		} else {
			List<Integer> roleIds = this.getauth(result.getId());
			authorities = roleIds.stream().map(roleId -> {
				return new SimpleGrantedAuthority(roleId + "");
			}).collect(Collectors.toList());
		}
		return new JwtUser(result, authorities);
	}

	@Override
	public int resetPassword(Integer userid) {
		User user = new User();
		user.setId(userid);
		user.setPassword((encoder.encode(Tool.MD5("123456"))));
		// TODO Auto-generated method stub
		return usermapper.updateByPrimaryKeySelective(user);
	}

	@Override
	public int changePassword(Integer userid, String oldpasssord, String newpassword) {
		// TODO Auto-generated method stub
		User user = usermapper.selectByPrimaryKey(userid);
		if (user == null) {
			// 没有找到用户
			return -1;
		}
		if (encoder.matches(oldpasssord, user.getPassword())) {
			user.setPassword(encoder.encode(newpassword));
			return usermapper.updateByPrimaryKeySelective(user);
		} else {
			// 旧密码不对
			return -2;
		}
	}

	@Override
	public User getUserInfo(User user) {
		if (user.getUniquecode() != null && !"".equals(user.getUniquecode())) {
			Example organExample = new Example(SysOrganization.class);
			organExample.createCriteria().andEqualTo("uniqueCode", user.getUniquecode());
			List<SysOrganization> organs = sysOrganizationMapper.selectByExample(organExample);

			if (organs.size() > 0) {
				user.setOrganId(organs.get(0).getId());
			}

			Example uExample = new Example(User.class);
			Criteria cU = uExample.createCriteria();
			cU.andEqualTo("enable", 1).andEqualTo("organId", user.getOrganId()).andEqualTo("username",
					user.getUsername());
			Criteria cA = uExample.createCriteria();
			cA.andEqualTo("type", -1).andEqualTo("username", user.getUsername());
			uExample.or(cA);

			List<User> list = usermapper.selectByExample(uExample);

			if (list.size() > 0) {

				return list.get(0);
			} else {

				return null;
			}
		} else {

			return null;
		}

	}

	@Override
	public int createUserByDirector(User user, Integer userid) {
		// TODO Auto-generated method stub
		User director = usermapper.selectByPrimaryKey(userid);
		if (director.getType() != 1) {
			// 没有权限
			return -1;
		}
		// 如果有权限，创建用户
		Example example = new Example(User.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("username", user.getUsername());
		List<User> resultList = usermapper.selectByExample(example);
		if (resultList.size() > 0) {
			// 用户名已存在
			return -2;
		}
		user.setCreateTime(new Date());
		user.setEnable(1);
		user.setType(2);
		user.setOrganId(director.getOrganId());
		user.setPassword(encoder.encode(Tool.MD5("123456")));
		int ok = usermapper.insertSelective(user);
		return ok;
	}

	@Override
	public PageInfo<User> getTeacherList(User user, int page, int size, int userid) {
		User director = usermapper.selectByPrimaryKey(userid);
		Map<Integer, String> map = new HashMap<>();
		List<SysOrganization> list = organmapper.selectAll();
		for (SysOrganization sysOrganization : list) {
			map.put(sysOrganization.getId(), sysOrganization.getName());
		}
		PageHelper.startPage(page, size);
		Example example = new Example(User.class);
		Example.Criteria criteria = example.createCriteria();
		if (StringUtil.isNotEmpty(user.getUsername())) {
			criteria.andLike("username", "%" + user.getUsername() + "%");
		}
		if (StringUtil.isNotEmpty(user.getRealname())) {
			criteria.andLike("realname", "%" + user.getRealname() + "%");
		}
		criteria.andEqualTo("organId", director.getOrganId());
		criteria.andEqualTo("type", 2);
		example.setOrderByClause(" create_time desc");
		List<User> resultList = usermapper.selectByExample(example);
		for (User user2 : resultList) {
			user2.setOrganname(map.get(user2.getOrganId()));
		}
		PageInfo<User> result = new PageInfo<User>(resultList);
		return result;
	}

	@Override
	public int editTeacher(User user) {
		user.setUsername(null);
		user.setPassword(null);
		user.setType(null);
		user.setOrganId(null);
		int ok = usermapper.updateByPrimaryKeySelective(user);
		return ok;
	}

	@Override
	public int deleteTeacher(Integer userid, Integer jwtUserid) {
		// TODO Auto-generated method stub
		if (userid == jwtUserid) {
			// 不能自己删自己
			return -1;
		}
		User director = usermapper.selectByPrimaryKey(jwtUserid);
		User user = usermapper.selectByPrimaryKey(userid);
		if (director == null || user == null) {
			// 找不到用户
			return 0;
		}
		if (user.getType() == 1) {
			// 不能删除主任
			return -2;
		}
		if (!user.getOrganId().equals(director.getOrganId())) {
			// 不能删除别的学校的教师
			return -3;
		}
		int ok = usermapper.deleteByPrimaryKey(userid);
		return ok;
	}

}